"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 硬件故障类--network
Case Name   : 主备切换时，备节点网络错报率3%
Create At   : 2021/07/30
@zou_jialiang0505328126
Description :
    1.备注入网络错包故障
    2.主备切换
Expect      :
    1.成功
    2.成功
History     :
    Modified by @wan005 2022/2/27:网络错包会导致环境SSH异常，调整错包率规避该问题
    Modified by wx1115623 2022/12/5:待故障结束再刷新配置文件
"""

import unittest
from yat.test import Node
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Logger import Logger


class NetWork(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(
            '---------Opengauss_Reliability_Hardware_Case078:开始执行---------')
        self.primary_root_node = Node(node='PrimaryRoot')
        self.sta_root_node = Node(node='Standby1Root')
        self.sta1_dbuser = Node(node='Standby1DbUser')
        self.com = Common()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.sta_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()

        self.log.info("-------------获取网卡名---------------")
        network_card_cmd = 'ifconfig'
        self.log.info(network_card_cmd)
        network_card_result = self.sta_root_node.sh(
            network_card_cmd).result()
        network_card_list = network_card_result.split('\n\n')
        self.log.info(network_card_list)
        self.networkcard = ''
        for network_card_item in network_card_list:
            if self.sta1_dbuser.db_host in network_card_item:
                self.networkcard = network_card_item.split(':')[0].strip()
                self.log.info(self.networkcard)

        self.hostmsg = self.primary_root_node.sh('hostname;').result()
        self.log.info(f'hostname is {self.hostmsg}')

    def test_main(self):
        self.log.info("--------------1.注入网络错包故障-------------")
        try:
            text = '----step1：注入网络错包故障 expect:成功----'
            inject_command = f"rNet_corrupt " \
                f"(dev, rate)values({self.networkcard}, " \
                f"{self.constant.network_error_rate})"
            result = self.com.cfe_inject(self.sta_root_node, inject_command)
            self.log.info(result)
            result = self.com.cfe_query(self.sta_root_node,
                                        f"rNet_corrupt where "
                                        f"dev={self.networkcard}")
            self.log.info(result)
            self.assertIn(f"corrupt {self.constant.network_error_rate}",
                          result, '执行失败:' + text)

            self.log.info("-------------2. 主备切换---------------")
            text = '----step2：主备切换 expect:成功----'
            result = self.sta_sh.executeGsctl('switchover',
                                              self.constant.SWITCH_SUCCESS_MSG)
            self.assertTrue(result, '执行失败:' + text)
        finally:
            self.log.info("--------------备节点清理故障-------------")
            result = self.com.cfe_clean(self.sta_root_node,
                                        f"rNet_corrupt where "
                                        f"dev={self.networkcard} and rate="
                                        f"{self.constant.network_error_rate}")
            self.log.info(result)
            result = self.com.cfe_query(self.sta_root_node,
                                        f"rNet_corrupt where "
                                        f"dev={self.networkcard}")
            self.log.info(result)
            result = self.sta_sh.exec_refresh_conf()
            self.assertTrue(result, '刷新配置文件失败')

    def tearDown(self):
        self.log.info("--------------恢复集群-------------")
        status = self.primary_sh.check_whether_need_switch(self.hostmsg)
        if status:
            self.primary_sh.executeGsctl('switchover',
                                         self.constant.SWITCHOVER_SUCCESS_MSG)
            self.primary_sh.exec_refresh_conf()
        self.log.info(
            '--------Opengauss_Reliability_Hardware_Case078:执行完成--------')
